import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getLoginUserUsingGet } from '@/api/userController'

// 从本地存储获取初始状态
const getInitialState = (): API.LoginUserVO => {
  const savedUser = localStorage.getItem('loginUser')
  if (savedUser) {
    try {
      return JSON.parse(savedUser)
    } catch (e) {
      localStorage.removeItem('loginUser')
    }
  }
  return {
    userName: '未登录',
  }
}

export const useLoginUserStore = defineStore('loginUser', () => {
  const loginUser = ref<API.LoginUserVO>(getInitialState())

  async function fetchLoginUser() {
    try {
      const res = await getLoginUserUsingGet()
      if (res.data.code === 0 && res.data.data) {
        console.log('获取到的用户信息：', res.data.data)
        loginUser.value = res.data.data
        // 更新本地存储
        localStorage.setItem('loginUser', JSON.stringify(res.data.data))
      } else {
        throw new Error('获取用户信息失败')
      }
    } catch (error) {
      console.error('获取登录用户信息出错:', error)
      // 清除本地存储和状态
      localStorage.removeItem('loginUser')
      loginUser.value = { userName: '未登录' }
    }
  }

  function setLoginUser(newLoginUser: API.LoginUserVO) {
    console.log('设置新的用户信息：', newLoginUser)
    loginUser.value = newLoginUser
    // 更新本地存储
    if (newLoginUser.userName === '未登录') {
      localStorage.removeItem('loginUser')
    } else {
      localStorage.setItem('loginUser', JSON.stringify(newLoginUser))
    }
  }

  return {
    loginUser,
    setLoginUser,
    fetchLoginUser,
  }
})
